package com.edevp.common.core.util.bean;

import com.google.common.collect.Lists;
import org.springframework.cglib.beans.BeanMap;

import java.util.List;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author Blueeyedboy
 * @create 2019-12-17 11:49 AM
 **/
public class BeanUtil {
	/**
	 *
	 * @Title: mapToObject
	 * @Description: TODO(map转换为bean)
	 * @return T    返回类型
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static <T> T map2Bean(Map<String, Object> map, Class<T> beanClass) throws Exception {
		if (map == null) {
			return null;
		}
		T obj = beanClass.newInstance();
		org.apache.commons.beanutils.BeanUtils.populate(obj, map);

		return obj;
	}

	/**
	 *
	 * @Title: objectToMap
	 * @Description: TODO(bean转换为Map)
	 * @return Map<?,?>    返回类型
	 * @param obj
	 * @return
	 */
	public static Map<?, Object> bean2Map(Object obj) {
		if(obj == null) {
			return null;
		}
		return new org.apache.commons.beanutils.BeanMap(obj);
	}


	/**
	 * 将对象装换为map
	 * @param bean
	 * @return
	 */
	public static <T> Map<String, Object> beanToMap(T bean) {

		return cn.hutool.core.bean.BeanUtil.beanToMap(bean);
	}

	/**
	 * 将map装换为javabean对象
	 * @param map
	 * @param bean
	 * @return
	 */
	public static <T> T mapToBean(Map<String, Object> map,T bean) {
//		return (T)cn.hutool.core.bean.BeanUtil.mapToBean(map,bean.getClass(),false, CopyOptions.create());
		BeanMap beanMap = BeanMap.create(bean);
		beanMap.putAll(map);
		return bean;

	}

	/**
	 * 将List<T>转换为List<Map<String, Object>>
	 * @param objList
	 * @return
	 */
	public static <T> List<Map<String, Object>> beanssToMaps(List<T> objList) {
		List<Map<String, Object>> list = Lists.newArrayList();
		if (objList != null && objList.size() > 0) {
			Map<String, Object> map = null;
			T bean = null;
			for (int i = 0,size = objList.size(); i < size; i++) {
				bean = objList.get(i);
				map = beanToMap(bean);
				list.add(map);
			}
		}
		return list;
	}

	/**
	 * 将List<Map<String,Object>>转换为List<T>
	 * @param maps
	 * @param clazz
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static <T> List<T> mapsToBeans(List<Map<String, Object>> maps,Class<T> clazz) throws InstantiationException, IllegalAccessException {
		List<T> list = Lists.newArrayList();
		if (maps != null && maps.size() > 0) {
			Map<String, Object> map = null;
			T bean = null;
			for (int i = 0,size = maps.size(); i < size; i++) {
				map = maps.get(i);
				bean = clazz.newInstance();
				mapToBean(map, bean);
				list.add(bean);
			}
		}
		return list;
	}

	public static void copyProperties(Object source, Object target)  {
		cn.hutool.core.bean.BeanUtil.copyProperties(source, target);
	}

}
